<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <div class="dashboard-header">
      <div class="header-left">
        <el-icon size="24" class="header-icon"><Monitor /></el-icon>
        <h1 class="header-title">网络监控中心</h1>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleRefreshInterval">
          <span class="refresh-dropdown">
            <el-icon><Timer /></el-icon>
            刷新间隔: {{ refreshInterval }}秒
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="10">10秒</el-dropdown-item>
              <el-dropdown-item command="30">30秒</el-dropdown-item>
              <el-dropdown-item command="60">1分钟</el-dropdown-item>
              <el-dropdown-item command="0">手动刷新</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <div class="last-update" v-if="lastUpdateTime">
          最后更新: {{ formatDateTime(lastUpdateTime) }}
        </div>
      </div>
    </div>

    <!-- 状态概览 -->
    <el-card shadow="always" class="overview-card">
      <div class="overview-content">
        <div class="overview-info">
          <h2>网络性能概览</h2>
          <p>实时监控您的网络连接状态与性能指标</p>
        </div>
        <div class="overview-buttons">
          <el-button 
            type="primary" 
            :loading="loading.current" 
            @click="fetchCurrentStatus" 
            icon="el-icon-refresh"
            size="large"
            class="refresh-btn"
          >
            刷新数据
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 关键指标卡片 -->
    <div class="metrics-section">
      <div class="metrics-grid">
        <StatusCard
          title="当前延迟"
          :value="currentStatus?.ping || '--'"
          unit="ms"
          :status="getPingStatus(currentStatus?.ping)"
          shadow="always"
        />
        <StatusCard
          title="下载速度"
          :value="currentStatus?.download_speed || '--'"
          unit="Mbps"
          :status="getSpeedStatus(currentStatus?.download_speed)"
          shadow="always"
        />
        <StatusCard
          title="上传速度"
          :value="currentStatus?.upload_speed || '--'"
          unit="Mbps"
          :status="getSpeedStatus(currentStatus?.upload_speed)"
          shadow="always"
        />
        <StatusCard
          title="网络状态"
          :value="currentStatus?.status_text || '--'"
          :status="getOverallStatus()"
          shadow="always"
        />
      </div>
    </div>

    <!-- 图表和控制面板 -->
    <div class="main-content">
      <!-- 左侧：历史趋势图 -->
      <el-card shadow="always" class="history-chart-card">
        <template #header>
          <div class="chart-header">
            <div class="chart-title">
              <el-icon><TrendCharts /></el-icon>
              <span>网络性能历史趋势</span>
            </div>
            <el-select 
              style="width: 120px;"
              v-model="historyDays" 
              placeholder="选择历史天数" 
              @change="fetchHistoryData"
              size="small"
              class="days-select right-aligned"
            >
              <el-option :label="'近7天'" :value="7" />
              <el-option :label="'近15天'" :value="15" />
              <el-option :label="'近30天'" :value="30" />
            </el-select>
          </div>
        </template>
        <div class="chart-wrapper">
          <ECharts 
            :options="historyChartOptions" 
            :loading="loading.history" 
            height="400px"
          />
        </div>
      </el-card>

      <!-- 右侧：实时监控控制 -->
      <el-card shadow="always" class="monitoring-panel">
        <MonitoringControl 
          @monitoring-status-change="handleMonitoringStatusChange"
          @mock-data-generated="handleMockDataGenerated"
          @refresh-data="refreshAllData"
        />
      </el-card>
    </div>


  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Monitor, 
  TrendCharts, 
  Timer, 
  ArrowDown 
} from '@element-plus/icons-vue';
import StatusCard from '../components/StatusCard.vue';
import ECharts from '../components/ECharts.vue';
import MonitoringControl from '../components/MonitoringControl.vue';
import networkService from '../api/networkService.js';

// 响应式数据
const currentStatus = ref(null);
const historyData = ref([]);
const historyDays = ref(7);
const statusTrends = ref({ ping: 0, download: 0, upload: 0 });
const lastUpdateTime = ref(null);
const refreshInterval = ref(60); // 默认60秒刷新一次
let refreshTimer = null;

// 加载状态管理
const loading = ref({
  current: false,
  history: false,
  mock: false,
  monitoring: false
});

// 计算属性


// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
};

// 获取延迟状态
const getPingStatus = (ping) => {
  if (!ping) return 'normal';
  if (ping > 100) return 'error';
  if (ping > 50) return 'warning';
  return 'success';
};

// 获取速度状态
const getSpeedStatus = (speed) => {
  if (!speed) return 'normal';
  if (speed < 10) return 'error';
  if (speed < 50) return 'warning';
  return 'success';
};

// 获取整体状态
const getOverallStatus = () => {
  if (!currentStatus.value) return 'normal';
  const { ping, download_speed, upload_speed } = currentStatus.value;
  
  if (getPingStatus(ping) === 'error' || 
      getSpeedStatus(download_speed) === 'error' || 
      getSpeedStatus(upload_speed) === 'error') {
    return 'error';
  }
  
  if (getPingStatus(ping) === 'warning' || 
      getSpeedStatus(download_speed) === 'warning' || 
      getSpeedStatus(upload_speed) === 'warning') {
    return 'warning';
  }
  
  return 'success';
};



// 历史图表配置 - 优化后的图表样式
const historyChartOptions = computed(() => {
  const dates = historyData.value.map(item => {
    const d = new Date(item.date);
    return `${d.getMonth() + 1}/${d.getDate()}`; // 简化显示格式
  });
  const pings = historyData.value.map(item => item.avg_ping);
  // 格式化 保留后两位小数
  const downloads = historyData.value.map(item => item.max_download.toFixed(2));
  // 格式化 保留后两位小数
  const uploads = historyData.value.map(item => item.max_upload.toFixed(2));
  
  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e0e0e0',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      data: ['平均延迟', '最大下载速度', '最大上传速度'],
      textStyle: {
        color: '#606266'
      },
      right: '10%',
      top: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      },
      axisLabel: {
        color: '#606266',
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '延迟 (ms)',
        position: 'left',
        axisLine: {
          lineStyle: {
            color: '#f56c6c'
          }
        },
        axisLabel: {
          color: '#606266',
          formatter: function(value) {
            return value.toFixed(2);
          }
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '速度 (Mbps)',
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#409eff'
          }
        },
        axisLabel: {
          color: '#606266',
          formatter: function(value) {
            return value.toFixed(2);
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '平均延迟',
        type: 'line',
        data: pings,
        yAxisIndex: 0,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#f56c6c'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(245, 108, 108, 0.3)'
            }, {
              offset: 1, color: 'rgba(245, 108, 108, 0.05)'
            }]
          }
        }
      },
      {
        name: '最大下载速度',
        type: 'line',
        data: downloads,
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#67c23a'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(103, 194, 58, 0.3)'
            }, {
              offset: 1, color: 'rgba(103, 194, 58, 0.05)'
            }]
          }
        }
      },
      {
        name: '最大上传速度',
        type: 'line',
        data: uploads,
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#409eff'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(64, 158, 255, 0.05)'
            }]
          }
        }
      }
    ],
    animation: true,
    animationDuration: 1000
  };
});

// 设置自动刷新
const setupAutoRefresh = () => {
  // 清除旧的定时器
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
  
  // 如果设置了自动刷新
  if (refreshInterval.value > 0) {
    console.log(`设置自动刷新间隔: ${refreshInterval.value}秒`);
    refreshTimer = setInterval(() => {
      fetchCurrentStatus();
    }, refreshInterval.value * 1000);
  }
};

// 处理刷新间隔变更
const handleRefreshInterval = (command) => {
  refreshInterval.value = Number(command);
  ElMessage.success(`已设置刷新间隔为${refreshInterval.value > 0 ? refreshInterval.value + '秒' : '手动刷新'}`);
  setupAutoRefresh();
};

// 获取当前状态
const fetchCurrentStatus = async () => {
  try {
    loading.value.current = true;
    const response = await networkService.getCurrentStatus();
    if (response.success) {
      const newData = response.data;
      
      // 计算趋势
      if (currentStatus.value) {
        statusTrends.value = {
          ping: newData.ping && currentStatus.value.ping ? 
            ((newData.ping - currentStatus.value.ping) / currentStatus.value.ping * 100) : 0,
          download: newData.download_speed && currentStatus.value.download_speed ?
            ((newData.download_speed - currentStatus.value.download_speed) / currentStatus.value.download_speed * 100) : 0,
          upload: newData.upload_speed && currentStatus.value.upload_speed ?
            ((newData.upload_speed - currentStatus.value.upload_speed) / currentStatus.value.upload_speed * 100) : 0
        };
      }
      
      // 处理数据来源标识，增强用户体验
      if (newData.data_source) {
        const sourceText = newData.data_source === 'real' ? '真实数据' : '模拟数据';
        console.log(`当前数据来源: ${sourceText}`);
      }
      
      currentStatus.value = newData;
      lastUpdateTime.value = new Date();
      
      // 添加日志信息
      console.log(`数据刷新成功: ping=${newData.ping}ms, download=${newData.download_speed}Mbps`);
    }
  } catch (error) {
    console.error('获取当前状态失败:', error);
    ElMessage.error('获取当前状态失败，请检查网络连接');
  } finally {
    loading.value.current = false;
  }
};

// 获取历史数据
const fetchHistoryData = async () => {
  try {
    loading.value.history = true;
    const response = await networkService.getHistoryData(historyDays.value);
    if (response.success) {
      historyData.value = response.data;
    }
  } catch (error) {
    ElMessage.error('获取历史数据失败');
  } finally {
    loading.value.history = false;
  }
};





// 处理监控状态变更
const handleMonitoringStatusChange = (isMonitoring) => {
  console.log('监控状态变更为:', isMonitoring ? '运行中' : '已停止');
  ElMessage.info(`监控状态已${isMonitoring ? '启动' : '停止'}`);
};

// 处理模拟数据生成
const handleMockDataGenerated = () => {
  console.log('模拟数据已生成');
};

// 刷新所有数据
const refreshAllData = async () => {
  try {
    await Promise.all([
      fetchCurrentStatus(),
      fetchHistoryData()
    ]);
  } catch (error) {
    console.error('刷新数据失败:', error);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  fetchCurrentStatus();
  fetchHistoryData();
  setupAutoRefresh();
});

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部导航栏样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: white;
}

.header-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.refresh-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border-radius: 6px;
  background-color: rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.refresh-dropdown:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.last-update {
  font-size: 14px;
  opacity: 0.9;
}

/* 概览卡片样式 */
.overview-card {
  margin-bottom: 24px;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.overview-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  flex-wrap: wrap;
  gap: 20px;
}

.overview-info h2 {
  margin: 0 0 6px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.overview-info p {
  margin: 0;
  color: #606266;
}

.overview-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.refresh-btn {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

/* 指标卡片样式 */
.metrics-section {
  margin-bottom: 24px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 20px;
}

/* 主内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 3fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

/* 历史图表卡片 */
.history-chart-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.right-aligned {
  margin-left: auto;
}

.chart-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.days-select {
  min-width: 120px;
}

.chart-wrapper {
  padding: 16px 0 20px;
}

/* 监控面板 */
.monitoring-panel {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 警报部分 */
.alerts-section {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}



/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 2fr 1fr;
  }
}

@media (max-width: 992px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .dashboard-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .header-right {
    flex-direction: column;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 12px;
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
  }
  
  .overview-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .overview-buttons {
    flex-direction: column;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .header-title {
    font-size: 20px;
  }
  
  .overview-info h2 {
    font-size: 18px;
  }
}
</style>